<template>
  <NFlex align="center" class="nv-toolbar">
    <slot name="toolbar_pre" :size="size" />

    <component :is="node" v-for="(node, index) in displayNodes" :key="index" :size />

    <slot name="toolbar" :size="size" />
  </NFlex>
</template>

<script setup lang="ts">
import type { NvToolbarOption } from '@/crud/types'
import type { Size } from '@/types'
import { NFlex } from 'naive-ui'
import { computed, unref } from 'vue'
import { useToolbar } from './use-toolbar'

interface Props {
  option?: NvToolbarOption | boolean
}
interface Emits {
  (e: 'refresh'): void
  (e: 'import'): void
  (e: 'export'): void
}
const props = defineProps<Props>()
const emits = defineEmits<Emits>()

const striped = defineModel<boolean>('striped', { required: true })
const loading = defineModel<boolean>('loading', { required: true })
const size = defineModel<Size>('size', { required: true })
const fullscreen = defineModel<boolean>('fullscreen', { required: true })

const showTooltips = computed(() => {
  if (typeof props.option === 'object') {
    return unref(props.option?.showTooltips) ?? true
  }
  return true
})

const { iconSize, nodes } = useToolbar({ striped, size, fullscreen, loading, showTooltips, emits })

const defaultNodes = [nodes.Striped, nodes.Divider, nodes.Refresh, nodes.Size, nodes.Fullscreen, nodes.ColumnSetting]
const displayNodes = computed(() => {
  if (typeof props.option === 'object') {
    return props.option?.render?.({ nodes, size, iconSize, loading, showTooltips }) || defaultNodes
  }
  return defaultNodes
})
</script>
